package com.only4play.practice.common.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author mdy
 * * @date 2024/9/30
 */
@Component
public class OrderNoGenUtils {

    @Resource
    private RedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "PAY";

    private static final String KEY_SEPARATOR = "-";

    /**
     * item.setChanTraPayOrderNo("{6位年月日}{6位自增码}{2位业务码}{3位随机数}，自增码位数根据业务数据而定，用redis自增过期时间一天");
     * @return 业务唯一id
     */
    public String genOrderNo(String bizCode) {
        //
        String dateFormatStr = DateFormatUtils.format(new Date(), DateFormatUtils.PATTERN_CLASSICAL_YMD);
        Random random = new Random();

        //6位自增码
        int randomStep = 1 +  random.nextInt(5);
        String redisKey = "gen_id_order_" + dateFormatStr;
        Long next = this.redisTemplate.opsForValue().increment(redisKey, randomStep);
        if (next == null){
            throw new RuntimeException("redis自增异常");
        }
        String stepString = String.format("%06d", next.intValue());

        bizCode = getBizValue(bizCode);

        //3位随机数
        int randomInt = 1 + random.nextInt(998);
        String randomString = String.format("%03d",randomInt);

        String orderId = dateFormatStr + stepString + bizCode + randomString;

        //设置redis的过期时间
        this.redisTemplate.expire(redisKey,3600 * (24+ 1), TimeUnit.SECONDS);//一天过期

        return orderId;
    }

    public String getBizValue(String bizCode){

        if (StrUtil.isEmpty(bizCode)){
            throw new RuntimeException("bizCode不能为空");
        }
        if (ObjectUtil.equals(bizCode,"paycenter")){
            return "01";
        }
        return KEY_PREFIX + KEY_SEPARATOR + bizCode;
    }
}
